package com.countertack.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.sql.ResultSet;

import net.lingala.zip4j.core.ZipFile;

import org.doublecloud.vi.vmware.guest.GuestFileDirector;
import org.json.JSONObject;

import com.countertack.impala.ImpalaConnector;
import com.countertack.ssh.SSHManager;
import com.vmware.vim25.GuestProgramSpec;
import com.vmware.vim25.NamePasswordAuthentication;
import com.vmware.vim25.mo.GuestAuthManager;
import com.vmware.vim25.mo.GuestOperationsManager;
import com.vmware.vim25.mo.GuestProcessManager;
import com.vmware.vim25.mo.VirtualMachine;

public class Utils {

	public static void installKBonVirtualMachine(SSHManager ssh,
			String[] kbFiles, VirtualMachine vm, GuestOperationsManager gom)
			throws Exception {

		if (vm != null && gom != null && ssh != null) {

			// copying tcpip kb
			for (String KbPath : kbFiles) {
				System.out.println("KBFile Path>>>>>" + KbPath);
				File kbFile = new File(KbPath);
				if (kbFile.exists()) {

					// GuestFileDirector fd = new GuestFileDirector(vm,
					// Configuration.getProperty("vmuser"),
					// Configuration.getProperty("vmpassword"));
					//
					// fd.uploadFile(KbPath,
					// Configuration.getProperty("vmdriverlocation")
					// + "\\" + kbFile.getName());

					ssh.copyFile(KbPath, kbFile.getName());

					// installing kbfile

					if (kbFile.getName().contains(".cab")) {

						// ssh.runCommand("cmd /c C:\\Windows\\System32\\pkgMgr.exe /ip /m:c:\\Users\\user\\"
						// + kbFile.getName() + " /quiet /norestart");

						GuestAuthManager gam = gom.getAuthManager(vm);
						NamePasswordAuthentication npa = new NamePasswordAuthentication();
						npa.username = Configuration.getProperty("vmuser");
						npa.password = Configuration.getProperty("vmpassword");
						;
						GuestProgramSpec spec = new GuestProgramSpec();
						spec.programPath = "C:\\Windows\\System32\\PkgMgr.exe";
						spec.arguments = "/ip /m:c:\\Users\\"
								+ Configuration.getProperty("vmuser") + "\\"
								+ kbFile.getName() + " /quiet /norestart";

						GuestProcessManager gpm = gom.getProcessManager(vm);
						long pid = gpm.startProgramInGuest(npa, spec);
						System.out.println("Process id>>>>" + pid);

						System.out.println(kbFile.getName()
								+ " Installed success fully");
						Thread.sleep(300000);

						// pkgMgr.exe /ip /m:c:\KB\$kb_value /quiet /norestart

					} else if (kbFile.getName().contains(".msu")) {
						//
						// ssh.runCommand("cmd /c wusa -s " + kbFile.getName()
						// + " /quiet /norestart");

						GuestAuthManager gam = gom.getAuthManager(vm);
						NamePasswordAuthentication npa = new NamePasswordAuthentication();
						npa.username = Configuration.getProperty("vmuser");
						npa.password = Configuration.getProperty("vmpassword");
						;
						GuestProgramSpec spec = new GuestProgramSpec();
						spec.programPath = "C:\\Windows\\System32\\wusa.exe";
						spec.arguments = "-s c:\\Users\\"
								+ Configuration.getProperty("vmuser") + "\\"
								+ kbFile.getName() + " /quiet /norestart";

						GuestProcessManager gpm = gom.getProcessManager(vm);
						long pid = gpm.startProgramInGuest(npa, spec);
						System.out.println("Process id>>>>" + pid);

						System.out.println(kbFile.getName()
								+ " Installed success fully");
						Thread.sleep(300000);
					} else if (kbFile.getName().contains(".exe")) {
						// ssh.runCommand("cmd /c " + kbFile.getName()
						// + " /quiet /norestart");

						GuestAuthManager gam = gom.getAuthManager(vm);
						NamePasswordAuthentication npa = new NamePasswordAuthentication();
						npa.username = Configuration.getProperty("vmuser");
						npa.password = Configuration.getProperty("vmpassword");
						;
						GuestProgramSpec spec = new GuestProgramSpec();
						spec.programPath = "c:\\Users\\"
								+ Configuration.getProperty("vmuser") + "\\"
								+ kbFile.getName();
						spec.arguments = "/quiet /norestart";

						GuestProcessManager gpm = gom.getProcessManager(vm);
						long pid = gpm.startProgramInGuest(npa, spec);
						System.out.println("Process id>>>>" + pid);

						System.out.println(kbFile.getName()
								+ " Installed success fully");
						Thread.sleep(300000);
					}

				}

			}

		}

	}

	public static String getTcpIPSymbol(SSHManager vmSsh) {
		String tcpIpsymchk = null;
		try {

			tcpIpsymchk = vmSsh
					.returnCommandOutPut("cmd /c cd \"C:\\Program Files\\"
							+ Configuration.getProperty("debugtoolname")
							+ "\" && symchk /v \"c:\\windows\\system32\\drivers\\tcpip.sys\"");

			if (tcpIpsymchk != null) {

				if (tcpIpsymchk.indexOf("C:\\Windows\\SYMBOLS\\tcpip.pdb") != -1) {

					tcpIpsymchk = tcpIpsymchk.substring(tcpIpsymchk
							.indexOf("C:\\Windows\\SYMBOLS\\tcpip.pdb")
							+ "C:\\Windows\\SYMBOLS\\tcpip.pdb".length());
					if (tcpIpsymchk.indexOf("tcpip.pdb") != -1) {

						tcpIpsymchk = tcpIpsymchk.substring(0,
								tcpIpsymchk.indexOf("tcpip.pdb"));

					}

				}

			}
		} catch (Exception e) {

			e.printStackTrace();
		}

		return tcpIpsymchk;
	}

	public static String getNtosKrnlSymbol(SSHManager vmSsh) {
		String ntosSymchk = null;
		try {
			ntosSymchk = vmSsh
					.returnCommandOutPut("cmd /c cd \"C:\\Program Files\\"
							+ Configuration.getProperty("debugtoolname")
							+ "\" && symchk /v \"c:\\windows\\system32\\ntoskrnl.exe\"");

			if (ntosSymchk != null) {
				// C:\Windows\SYMBOLS\ntkrnlmp.pdb\
				if (ntosSymchk.indexOf("C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb") != -1) {

					ntosSymchk = ntosSymchk.substring(ntosSymchk
							.indexOf("C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb")
							+ "C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb".length());
					if (ntosSymchk.indexOf("ntkrnlmp.pdb") != -1) {

						ntosSymchk = ntosSymchk.substring(0,
								ntosSymchk.indexOf("ntkrnlmp.pdb"));

					}

				}

			}

		} catch (Exception e) {

			e.printStackTrace();
		}

		return ntosSymchk;
	}

	public static String getNtosKrnlpaSymbol(SSHManager vmSsh) {
		String ntosSymchk = null;
		// C:\Windows\SYMBOLS\ntkrpamp.pdb\
		try {
			ntosSymchk = vmSsh
					.returnCommandOutPut("cmd /c cd \"C:\\Program Files\\"
							+ Configuration.getProperty("debugtoolname")
							+ "\" && symchk /v \"c:\\windows\\system32\\ntkrnlpa.exe\"");

			if (ntosSymchk != null) {
				// C:\Windows\SYMBOLS\ntkrnlmp.pdb\
				if (ntosSymchk.indexOf("C:\\Windows\\SYMBOLS\\ntkrpamp.pdb") != -1) {

					ntosSymchk = ntosSymchk.substring(ntosSymchk
							.indexOf("C:\\Windows\\SYMBOLS\\ntkrpamp.pdb")
							+ "C:\\Windows\\SYMBOLS\\ntkrpamp.pdb".length());
					if (ntosSymchk.indexOf("ntkrpamp.pdb") != -1) {

						ntosSymchk = ntosSymchk.substring(0,
								ntosSymchk.indexOf("ntkrpamp.pdb"));

					}

				}

			}

		} catch (Exception e) {

			e.printStackTrace();
		}

		return ntosSymchk;
	}

	public static String getEndpointId(ImpalaConnector iConnector, String vmIp)
			throws Exception {
		String eId = null;
		try {

			ResultSet endpointIdRes = iConnector
					.executeQueryAndReturnResults("select id from endpoints where ip='"
							+ vmIp
							+ "'"
							+ " and status='ON' and ip is not null order by time_started asc limit 1");

			while (endpointIdRes.next()) {
				try {
					eId = endpointIdRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println("endpoint Id>>>>>>" + eId);

			}

		} finally {

			return eId;

		}

	}

	public static String getUnsupportedEndpointId(ImpalaConnector iConnector,
			String vmIp) throws Exception {
		String eId = null;
		try {

			/*
			 * ResultSet endpointIdRes = iConnector
			 * .executeQueryAndReturnResults
			 * ("select id from endpoints where ip='" + vmIp + "'" +
			 * " and status='INIT' and ip is not null order by time_started asc limit 1"
			 * );
			 */
			ResultSet endpointIdRes = iConnector
					.executeQueryAndReturnResults("select id from endpoints where status='INIT'  and ip='"
							+ vmIp
							+ "' and ip is not null order by time_started asc limit 1");

			while (endpointIdRes.next()) {
				try {
					eId = endpointIdRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println("endpoint Id>>>>>>" + eId);

			}

		} finally {

			return eId;

		}

	}

	public static String getExtractedFileStatus(ImpalaConnector iConnector,
			String extractionId) throws Exception {
		String extractionStatus = null;

		try {
			ResultSet endpointIdRes = iConnector
					.executeQueryAndReturnResults("select status from extracted_files where id='"
							+ extractionId + "'");

			while (endpointIdRes.next()) {
				try {
					extractionStatus = endpointIdRes.getString(1);
				} catch (Exception e) {

				}

				System.out
						.println("Extractin statusF>>>>>>" + extractionStatus);

			}

		} finally {
			return extractionStatus;

		}

	}

	public static void InstallKernalModuleOnEndpointmachine(
			SSHManager endpointSsh, String vmUser, String sentenelIp,
			boolean isXpMachine) throws Exception {

		endpointSsh.copyFile(Configuration.getProperty("driverpath"),
				"CounterTack Agent Installer Hiding.exe");
		if (isXpMachine) {

			endpointSsh.runCommand("cmd /c \"C:\\Documents and Settings\\"
					+ vmUser
					+ "\\CounterTack Agent Installer Hiding.exe\" /S /HOST:"
					+ sentenelIp + " /PORT:443");
		} else {

			endpointSsh.runCommand("cmd /c \"C:\\Users\\" + vmUser
					+ "\\CounterTack Agent Installer Hiding.exe\" /S /HOST:"
					+ sentenelIp + " /PORT:443");
		}

		System.out.println("Installing agent on endpoint");
		Thread.sleep(120000);

	}

	public static void pauseEndpoint(String eid) throws Exception {

		String pause = "{ " + "  \"type\":\"pause_many\", "
				+ "  \"endpoints\":[ " + "\"" + eid + "\" " + " ] " + "} ";

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", pause);

	}

	public static void resumeEndpoint(String eid) throws Exception {

		String resume = "{ " + "  \"type\":\"resume_many\", "
				+ "  \"endpoints\":[ " + "    \"" + eid + "\" " + "] " + "} ";

		HttpClientUtils.composePostRequest(
				Configuration.getProperty("restapirooturi")
						+ "/endpoints/command", resume);

	}

	public static void downloadExtractedFile(String sentinelIp,
			String fileExtractionId) {
		try {

			SSHManager sentinelSsh = new SSHManager("root", "f00b@r",
					sentinelIp);
			sentinelSsh.connect();

			sentinelSsh.runCommand("hadoop fs -copyToLocal /extracted_files/"
					+ fileExtractionId + ".zip " + fileExtractionId + ".zip");
			sentinelSsh.downloadFile("/root/" + fileExtractionId + ".zip",
					fileExtractionId + ".zip");

			System.out.println("extracted file downloaded success fully");
			sentinelSsh.closeSession();
			sentinelSsh.doReconnect = false;

		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	public static void unzipFile(String source, String destination,
			String password) {

		try {
			ZipFile zipFile = new ZipFile(source);
			if (zipFile.isEncrypted()) {
				zipFile.setPassword(password);
			}
			zipFile.extractAll(destination);

		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	public static String getDriverVersion(String sentinelIp, String endpointId) {
		String kernalModule_Version = null;
		try {

			ImpalaConnector iConnector = ImpalaConnector
					.createImpalaConnectorInstance(sentinelIp);
			kernalModule_Version = getDriverVersion(endpointId, iConnector);
			iConnector.closeImpalaConnection();

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			return kernalModule_Version;
		}

	}

	public static String getEndpointIdFromBehaviorId(String sentinelIp,
			String behaviorId)

	{
		String eId = null;
		ImpalaConnector iConnector = null;
		try {

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);

			ResultSet endpointIdRes = iConnector
					.executeQueryAndReturnResults("select endpoint_id from behaviors_denorm where hex(behavior_id)='"
							+ behaviorId
							+ "' and hex(behavior_id) is not null limit 1");

			while (endpointIdRes.next()) {
				try {
					eId = endpointIdRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println("endpoint Id>>>>>>" + eId);

			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();
				}
			} catch (Exception e) {

			}

			return eId;
		}

	}

	public static String getDriverVersion(String eid, ImpalaConnector iConnector) {

		String driver_Version = null;
		ResultSet endpointStatRes = iConnector
				.executeQueryAndReturnResults("select driver_version from endpoints where id='"
						+ eid + "'");
		try {
			while (endpointStatRes.next()) {
				try {
					driver_Version = endpointStatRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println("Driver version>>>>>>" + driver_Version);

			}
		} catch (Exception e) {

		}

		return driver_Version;

	}

	public static void main(String[] args) throws Exception {
		/*
		 * SSHManager ssh = new SSHManager("user", "password1",
		 * "10.140.63.115"); ssh.connect();
		 * Configuration.loadProperties("config.properties");
		 * 
		 * String tcpIpsymchk = ssh .returnCommandOutPut(
		 * "cmd /c cd \"C:\\Program Files\\Debugging Tools for Windows\""
		 * 
		 * + "&& symchk /v \"c:\\windows\\system32\\drivers\\tcpip.sys\"");
		 * 
		 * System.out.println("val>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" +
		 * tcpIpsymchk);
		 */

		// Utils.installKBonVirtualMachine(
		// ssh,
		// new String[] {
		// "C:\\Users\\user\\Desktop\\kbs\\2868623\\windows6.1-kb2868623-x64_c747dd8b5c03e5c3f0679edf983f1b6110809690.cab",
		// "C:\\Users\\user\\Desktop\\kbs\\2709715\\windows6.1-kb2709715-x64_d803e569afc50efbbf348b2776b77d8f5b3e6b46.cab"
		// });

		try {
			RandomAccessFile f = new RandomAccessFile("mb.txt", "rw");
			f.setLength(1024 * 1024 * 2 + 2);
			/*
			 * unzipFile("extracted_files-0000001392619820262-0273038901temp.zip"
			 * , "extracted_files-0000001392619820262-0273038901temp",
			 * "sentinel");
			 */

		} catch (Exception e) {
			System.err.println(e);
		}

	}

	public static String extractFile(String fileExtractionPayload) {

		String fileExtPostRes = null;
		String fileExtId = null;
		try {
			System.out.println("payload>>" + fileExtractionPayload);
			fileExtPostRes = HttpClientUtils.composePostRequest(
					Configuration.getProperty("restapirooturi")
							+ "/extractedfiles", fileExtractionPayload);
			System.out.println("File extraction response>>>" + fileExtPostRes);

			JSONObject jsonFilextRes = new JSONObject(fileExtPostRes);

			fileExtId = jsonFilextRes.optString("id");

		} catch (Exception pstEx) {

		} finally {

			return fileExtId;
		}

	}

	public static void addResultsToLog(StringBuffer vals, String resultCase,
			String vmName) {
		File testCaseResFile = new File(resultCase + "_"
				+ Configuration.getProperty("vmname") + ".txt");

		try {
			testCaseResFile.createNewFile();
			FileOutputStream fout = new FileOutputStream(testCaseResFile);

			//

			fout.write(vals.toString().getBytes());

			fout.flush();
			fout.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}
	
	public static String getEndpointValFromBehaviors_denorm(String eId,String sentinelIp,String col_name){
		
		
		String action=null;
		
		ImpalaConnector iConnector = null;
		try {

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);

			ResultSet actionRes = iConnector
					.executeQueryAndReturnResults("select "+col_name+" from behaviors_denorm where endpoint_id='"+eId+"' and "+col_name+" is not null limit 1");

			while (actionRes.next()) {
				try {
					action = actionRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println(col_name+">>>>>>" + action);

			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();
				}
			} catch (Exception e) {

			}

			return action;
		}

		
		
	}
	
	

	public static String getEndpointValFromNotifications(String eId,String sentinelIp,String col_name){
		
		
		String action=null;
		
		ImpalaConnector iConnector = null;
		try {

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);

			ResultSet actionRes = iConnector
					.executeQueryAndReturnResults("select "+col_name+" from notifications where  related_object_id like '%"+eId+"%' and "+col_name+" is not null limit 1");

			while (actionRes.next()) {
				try {
					action = actionRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println(col_name+">>>>>>" + action);

			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();
				}
			} catch (Exception e) {

			}

			return action;
		}

		
		
	}

	
	
	public static String getEndpointValFromBehaviors(String eId,String sentinelIp,String col_name){
		
		
		String action=null;
		
		ImpalaConnector iConnector = null;
		try {

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);
			ResultSet actionRes =null;
if(col_name.equalsIgnoreCase("behavior_type")){
	
	actionRes = iConnector
			.executeQueryAndReturnResults("select "+col_name+" from behaviors_plus where uri like '%"+eId+"%' limit 1");
}else{
	actionRes = iConnector
			.executeQueryAndReturnResults("select "+col_name+" from behaviors_plus where uri like '%"+eId+"%' and "+col_name+" is not null limit 1");
	
}
			

			while (actionRes.next()) {
				try {
					action = actionRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println(col_name+">>>>>>" + action);

			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();
				}
			} catch (Exception e) {

			}

			return action;
		}

		
		
	}
	
	
	
public static String getEndpointValFromEndpoints(String eId,String sentinelIp,String col_name){
		
		
		String action=null;
		
		ImpalaConnector iConnector = null;
		try {

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);

			ResultSet actionRes = iConnector
					.executeQueryAndReturnResults("select "+col_name+" from endpoints where id='"+eId+"' and "+col_name+" is not null limit 1");

			while (actionRes.next()) {
				try {
					action = actionRes.getString(1);
				} catch (Exception e) {

				}

				System.out.println(col_name+">>>>>>" + action);

			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();
				}
			} catch (Exception e) {

			}

			return action;
		}

		
		
	}
	
	
	
	
}
